<template>
  <el-dialog :title="title" :show-close="false" :close-on-click-modal="false" :close-on-press-escape="false" :destroy-on-close="true" :visible.sync="visible" :width="'480px'">
    <el-form :model="tagForm" :ref="tagForm" label-width="100px" size="small">
      <el-form-item label="标签名称" required>
        <el-input size="small" v-model.trim="tagForm.name" placeholder="请输入标签名" maxlength="10" show-word-limit @input="watchInput($event, 'name')"></el-input>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="cancel()">取 消</el-button>
      <el-button type="primary" :loading="submitLoading" @click="confirm()">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { SaveStoreTagItem } from '@/views/store-management/services/index'
export default {
  props: ['visible', 'tagId', 'tagName'],
  data() {
    return {
      tagForm: {
        name: '',
      },
      submitLoading: false,
    }
  },
  watch: {
    visible: {
      immediate: true,
      handler(newValue) {
        if (!newValue) return
        this.tagForm.name = this.tagName
      },
    },
  },
  computed: {
    title() {
      return this.tagId ? '编辑标签' : '新建标签'
    },
  },
  methods: {
    watchInput(event, key) {
      this.tagForm[key] = this.inputReplaceSpecialChar(event)
    },

    //清空表单信息
    clearForm() {
      this.tagForm.name = ''
    },
    confirm() {
      if (!this.tagForm.name) {
        this.$message.warning('请输入标签名称!')
        return
      }
      this.submitLoading = true
      SaveStoreTagItem({
        id: this.tagId,
        name: this.tagForm.name,
        // 用户ID之后需要修改
        creatorId: JSON.parse(this.$store.getters.userInfo).id ? JSON.parse(this.$store.getters.userInfo).id : '1',
      })
        .finally(() => (this.submitLoading = false))
        .then(data => {
          if (data && data.code == 200) {
            this.$message.success((this.tagId ? '新建' : '修改') + '成功!')
            this.clearForm()
            this.$emit('update:visible', false)
            this.$emit('update')
          } else {
            this.$message.success((this.tagId ? '新建' : '修改') + '失败!')
          }
        })
    },
    cancel() {
      this.clearForm()
      this.$emit('update:visible', false)
    },
  },
}
</script>
